<?php
// 启动会话
session_start();

// 检查是否已登录
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

// 检查是否为POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '无效的请求方法']);
    exit;
}

// 引入数据库配置
require_once '../config.php';

// 获取POST数据
$newUsername = $_POST['new_username'] ?? '';

// 验证输入
if (empty($newUsername)) {
    echo json_encode(['success' => false, 'message' => '请输入新用户名']);
    exit;
}

if (strlen($newUsername) < 3 || strlen($newUsername) > 20) {
    echo json_encode(['success' => false, 'message' => '用户名长度必须在3-20个字符之间']);
    exit;
}

// 检查用户名是否已存在
$stmt = $pdo->prepare("SELECT id FROM admins WHERE username = :username");
$stmt->bindParam(':username', $newUsername, PDO::PARAM_STR);
$stmt->execute();

if ($stmt->rowCount() > 0) {
    echo json_encode(['success' => false, 'message' => '用户名已存在，请选择其他用户名']);
    exit;
}

// 更新用户名
$adminId = $_SESSION['admin_id'];
$stmt = $pdo->prepare("UPDATE admins SET username = ? WHERE id = ?");
$stmt->bindParam(1, $newUsername, PDO::PARAM_STR);
$stmt->bindParam(2, $adminId, PDO::PARAM_INT);

if ($stmt->execute()) {
    // 更新会话中的用户名
    $_SESSION['admin_username'] = $newUsername;
    echo json_encode(['success' => true, 'message' => '用户名修改成功！']);
} else {
    echo json_encode(['success' => false, 'message' => '用户名修改失败，请稍后再试']);
}

$stmt->closeCursor();
$pdo = null;
?>